<template>
  <el-card shadow="never" v-if="skuList.length > 0">
    <div slot="header">
      <span>SPU下已有SKU展示</span>
    </div>
    <SkusTable
      :maxTableHeight="480"
      :columns="TableInfo.columns"
      :dataSource="TableInfo.list"
    />
  </el-card>
</template>
<script>
import SkusTable from '@/components/skusTable';
import { TableInfo } from '@/utils/getUtils';
import { getDetailedListByAttrUuidService } from '@/api/public';
export default {
  components: {
    SkusTable
  },
  props: {
    headerList: {
      type: Array,
      default: () => []
    },
    skuList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      TableInfo: new TableInfo(),
      selectLoading: false,
      attrMaps: new Map()
    }
  },
  watch: {
    skuList: {
      handler () {
        this.updateTableColumns()
        this.TableInfo.setList(this.getFormatTableList())
      },
      immediate: true
    }
  },
  methods: {
    // 加载下拉options
    async handleLoadSelectOptions (row, attrUuid) {
      const data = { attrUuid }
      const loadingFn = state => { this.selectLoading = state }
      const res = await getDetailedListByAttrUuidService(data, loadingFn)
      this.$set(row, 'selectOptions', res?.retData)
    },
    // 选择规格属性
    handleSelectSpec (row, val, attributeUuid) {
      const specVo = (row?.selectOptions ?? []).find(item => item.attrValue == val)
      const [valueUuidKey, valueNameKey] = this.getValueKeys(row.skuNo, attributeUuid)
      row[valueUuidKey] = specVo?.attrValueUuid ?? ''
      row[valueNameKey] = val
    },
    // 更新表格表列
    updateTableColumns () {
      const columns = [
        { title: 'SKU编码', key: 'skuNo' },
        ...this.getColumnsByChangeHeaderList(),
        {
          title: '规格',
          render: (h, { row }) => <span>{this.getSpecListStr(row)}</span>
        }
      ]
      this.TableInfo.setColumns(columns)
    },
    // 获取属性值id和name的字段key
    getValueKeys (skuNo, attrValueUuid) {
      const uuid = `${skuNo}_${attrValueUuid}_valueUuid`
      const name = `${skuNo}_${attrValueUuid}_valueName`
      return [uuid, name]
    },
    // 获取规格文本
    getSpecListStr (row) {
      const specStr = this.headerList
        .map(item => row[item.attributeUuid])
        .filter(item => item)
        .join('/')
      return specStr
    },
    // 获取格式化后的表格数据
    getFormatTableList () {
      const updateList = this.skuList.reduce((value, item) => {
        const specList = item?.specList ?? []
        let skuVo = { skuNo: item.skuNo }
        specList.forEach(specItem => {
          const [valueUuidKey, valueNameKey] = this.getValueKeys(item.skuNo, specItem.attributeUuid)
          skuVo = {
            ...skuVo,
            [specItem.attributeUuid]: specItem.valueName,
            [valueUuidKey]: specItem.valueUuid,
            [valueNameKey]: specItem.valueName
          }
        })
        value.push(skuVo)
        return value
      }, [])
      return updateList
    },
    // 获取提交所需的skuInputList
    getSkuInputList () {
      const skuInputList = this.TableInfo.list.map(item => ({
        skuNo: item.skuNo,
        specList: _.orderBy(this.getSpecList(item), ['position'], ['asc'])
      }))
      return skuInputList
    },
    // 获取skuInputList的specList
    getSpecList (row) {
      let specList = []
      for (const key in row) {
        if (!this.attrMaps.has(key)) continue
        const [valueUuidKey, valueNameKey] = this.getValueKeys(row.skuNo, key)
        specList.push({
          valueUuid: row[valueUuidKey],
          valueName: row[valueNameKey],
          ..._.pick(this.attrMaps.get(key), ['attributeUuid', 'attributeName', 'position']),
        })
      }
      return specList
    },
    // 获取headerList转换后的表列集合
    getColumnsByChangeHeaderList () {
      const headerColumns = this.headerList.map(item => {
        this.attrMaps.set(item.attributeUuid, item)
        const curColumn = {
          title: item.attributeName,
          key: item.attributeUuid,
          render: (h, { row, col }) => (
            <el-select
              v-model={ row[item.attributeUuid] }
              placeholder="请选择"
              remote={true}
              clearable={true}
              filterable={true}
              allow-create={true}
              loading={this.selectLoading}
              onFocus={() => { this.handleLoadSelectOptions(row, col?.property) }}
              onChange={val => { this.handleSelectSpec(row, val, col?.property) }}
            >
              {(row.selectOptions ?? []).map(item =>
                <el-option
                  key={item.attrValueUuid}
                  label={item.attrValue}
                  value={item.attrValue}
                  disabled={item.attrValue == '通用'}
                />
              )}
            </el-select>
          )
        }
        return curColumn
      })
      return headerColumns
    },
    handleClick () {
      this.getSkuInputList()
    },

  }
}
</script>
